package com.hopu.oa.controller.user;


import com.hopu.oa.entity.dto.user.UserInformation;
import com.hopu.oa.entity.mail.Mailreciver;
import com.hopu.oa.entity.notice.AoaNoticeList;
import com.hopu.oa.entity.user.AoaNotepaper;
import com.hopu.oa.entity.user.AoaUser;
import com.hopu.oa.service.impl.mail.mailServiceImpl;
import com.hopu.oa.service.impl.notice.AoaNoticeListServiceImpl;
import com.hopu.oa.service.impl.user.UserPlaneServiceImp;
import com.hopu.oa.service.user.UserService;
import com.hopu.oa.until.MD5Util;
import com.hopu.oa.until.OosUtil;
import com.hopu.oa.until.data.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserPlaneController   用户面板
 * @Description: 修改用户
 * @Date: 2021/11/11 15:30
 */


@Controller
public class UserPlaneController {

    // oos 工具类   -> DI ,用来更新头像
    @Autowired
    private OosUtil oosUtil;


    // 用户面板 UserPlaneService  -> DI
    @Autowired
    private UserService userService;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    //用户标签
    @Autowired
    private UserPlaneServiceImp userPlaneServiceImp;
    @Autowired
    private AoaNoticeListServiceImpl aoaNoticeListService;

    @Autowired
    private mailServiceImpl mailService;


    /*
      @Description : 用户信息修改：
                                1. 头像修改

      @Date   :  2021/11/12
      @Param  : [aoaUser, file]
      @return : java.lang.String
     */
    @RequestMapping("saveuser")
    public String saveuser(UserInformation userInformation,  //普通字段 映射到UserInformation实体类
                           @RequestParam("filePath") MultipartFile file,     //头像
                           HttpSession session) throws Exception {

        /**
         * 修改后的新密码进行加密
         */
        String password = userInformation.getPassword();
        String md5Encode = MD5Util.md5Encode(password);
        userInformation.setPassword(md5Encode);


        //DTO user
        UserInformation dtoUser = userInformation;

        //AoaUser
        AoaUser aoaUser = (AoaUser) session.getAttribute("user");

        // 判断是否修改头像，修改 : 上传头像并将url赋值给DTOUser的头像字段
        // 判断是否修改头像，修改 : 上传头像并将url赋值给DTOUser的头像字段
        if (file.getSize() != 0) {
            //dtoUser.setImgPath(oosUtil.getImgUrl(oosUtil.uploadImg2Oss(file)));
           /* String url =  new T2().uploadFileAvatar(file);
            System.out.println(url);*/

            String filename = file.getOriginalFilename();
            if (!"".equals(filename.trim())) {
                File newFile = new File(filename);
                FileOutputStream os = new FileOutputStream(newFile);
                os.write(file.getBytes());
                os.close();
                file.transferTo(newFile);
                //上传到OSS
                String uploadUrl = aliyunOSSUtil.upload(newFile);
                String url = "https://2oa-file.oss-cn-beijing.aliyuncs.com/";
                dtoUser.setImgPath(url + uploadUrl);
            }
        }


        //获取用户，和flag
        Map<String, Object> map = userService.user_updateUserByUserId(aoaUser, dtoUser);
        //删除当前用户
        session.removeAttribute("user");


        //flag为true ，修改了密码，踢到 登录页
        if ((boolean) map.get("flag")) {
            return "redirect:login";
        }

        session.setAttribute("user", (AoaUser) map.get("user"));
        // 做了一些普通修改，重新请求一下页面
        return "redirect:userpanel";
    }

    /**
     * 外层分页
     *
     * @param page
     * @param size
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("userpanel")
    public String queryNotepaper(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "8") int size, Model model, HttpSession session) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        // 跳页面之前查询用户职位，部门名称
        Map<String, String> map = userService.queryUserDeptAndPositionById(user.getUserId());
        model.addAttribute("positionname", map.get("positionName"));
        model.addAttribute("deptname", map.get("deptName"));

        //总数量
        int totalElements = userPlaneServiceImp.queryNotepaper(user.getUserId(), page, 0).size();
        //有几页
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<AoaNotepaper> notepaperlist = userPlaneServiceImp.queryNotepaper(user.getUserId(), (page - 1) * size, size);
        System.out.println(notepaperlist);
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);
        model.addAttribute("page", map1);
        model.addAttribute("notepaperlist", notepaperlist);
        model.addAttribute("url", "selNotepaper");

        List<Mailreciver> noreadlist = mailService.findByReadAndDelAndReciverId(0, 0, user.getUserId());
        model.addAttribute("mail", noreadlist.size());
        System.out.println("noreadlist = " + noreadlist.size());
        List<AoaNoticeList> aoaNoticeLists = aoaNoticeListService.queryNoticeListById(user.getUserId(), null, 0, 0);
        model.addAttribute("notice", aoaNoticeLists.size());
        System.out.println("aoaNoticeLists.size() = " + aoaNoticeLists.size());

        return "user/userpanel";
    }

    //标签模块

    /**
     * 内层分页
     *
     * @param page
     * @param size
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/selNotepaper")
    public String selNotepaper(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "8") int size, Model model, HttpSession session) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        //总数量
        int totalElements = userPlaneServiceImp.queryNotepaper(user.getUserId(), page, 0).size();
        //有几页
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<AoaNotepaper> notepaperlist = userPlaneServiceImp.queryNotepaper(user.getUserId(), (page - 1) * size, size);
        System.out.println(notepaperlist);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("totalElements", totalElements);
        map.put("totalPages", totalPages);
        map.put("number", page);
        map.put("size", size);

        model.addAttribute("page", map);
        model.addAttribute("notepaperlist", notepaperlist);
        model.addAttribute("url", "selNotepaper");
        List<Mailreciver> noreadlist = mailService.findByReadAndDelAndReciverId(0, 0, user.getUserId());
        model.addAttribute("mail", noreadlist.size());
        System.out.println("noreadlist = " + noreadlist.size());
        List<AoaNoticeList> aoaNoticeLists = aoaNoticeListService.queryNoticeListById(user.getUserId(), null, 0, 0);
        model.addAttribute("notice", aoaNoticeLists.size());
        System.out.println("aoaNoticeLists.size() = " + aoaNoticeLists.size());
        return "user/panel";
    }

    /**
     * 添加和修改
     *
     * @param notepaper
     * @param session
     * @return
     */
    @RequestMapping("writep")
    public String addNotepaper(AoaNotepaper notepaper, @RequestParam("number") String page, HttpSession session, HttpServletRequest request) {

        AoaUser user = (AoaUser) session.getAttribute("user");

        if (notepaper.getNotepaperId() != null) {
            userPlaneServiceImp.updateNotepaper(notepaper);
            return "redirect:userpanel?page=" + page;

        } else {
            Integer userId = user.getUserId();
            notepaper.setNotepaperUserId(userId);
            //使用Calendar 获取当前日期和时间

            Date date = new Date();
            //转换格式 使用format将这个日期转换成我们需要的格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(formatter.format(date));

            notepaper.setCreateTime(formatter.format(date));
            System.out.println(notepaper);
            userPlaneServiceImp.addNotepaperById(notepaper);
            return "redirect:userpanel";

        }

    }

    /**
     * 添加
     *
     * @param notepaper
     * @param session
     * @return
     */
    @RequestMapping("writep2")
    public String addNotepaper2(String concent, AoaNotepaper notepaper, HttpSession session) {

        AoaUser user = (AoaUser) session.getAttribute("user");

        AoaNotepaper notepaper2 = new AoaNotepaper();
        notepaper2.setConcent(concent);
        Integer userId = user.getUserId();
        notepaper2.setNotepaperUserId(userId);
        //使用Calendar 获取当前日期和时间
        Date date = new Date();
        //转换格式 使用format将这个日期转换成我们需要的格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(formatter.format(date));
        notepaper2.setCreateTime(formatter.format(date));

        System.out.println(notepaper2);
        userPlaneServiceImp.addNotepaperById(notepaper2);
        return "redirect:index";


    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping("notepaper")
    public String deleteNotepaperById(int id, HttpServletRequest request) {
        String page = request.getParameter("page");
        userPlaneServiceImp.deleteNotepaper(id);
        return "redirect:userpanel?page=" + page;
    }


}
